package com.pig4cloud.pig.itinerary.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.itinerary.api.dto.TrItineraryAddDTO;
import com.pig4cloud.pig.itinerary.api.entity.TrItinerary;
import com.pig4cloud.pig.itinerary.api.entity.TrItineraryContent;
import com.pig4cloud.pig.itinerary.mapper.TrItineraryMapper;
import com.pig4cloud.pig.itinerary.service.TrItineraryContentService;
import com.pig4cloud.pig.itinerary.service.TrItineraryService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

import static cn.hutool.core.date.DateTime.now;

@Service
@AllArgsConstructor
public class TrItineraryServiceImpl extends ServiceImpl<TrItineraryMapper, TrItinerary> implements TrItineraryService {
	private final TrItineraryMapper trItineraryMapper;
	private final TrItineraryContentService itineraryContentService;

	@Override
	public IPage<TrItinerary> selectItineraryByCondition(Page page, String itineraryName, String createBy) {
		return trItineraryMapper.selectItineraryByCondition(page, itineraryName, createBy);
	}
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Long addItineraryWithContent(TrItineraryAddDTO dto) {
		// 1. 转换DTO为行程库实体并保存
		TrItinerary itinerary = new TrItinerary();
		itinerary.setItineraryName(dto.getItineraryName());
		itinerary.setDelFlag('0'); // 默认为未删除
		itinerary.setCreateBy(SecurityUtils.getUser().getName());
		itinerary.setRemark(dto.getRemark());
		itinerary.setCreateTime(now()); // 使用Java 8的时间API更推荐
		this.save(itinerary);
		// 2. 获取自动生成的行程库ID
		Long itineraryId = itinerary.getItineraryId();
		if (itineraryId == null) {
			throw new RuntimeException("行程库创建失败，未生成ID"); // 增加异常处理
		}
		// 3. 处理关联的行程内容列表
		List<TrItineraryContent> contentList = dto.getTrItineraryContents();
		if (contentList != null && !contentList.isEmpty()) {
			contentList.forEach(content -> {
				// 设置关联的行程库ID
				content.setItineraryId(itineraryId); // 子表关联主表ID
				content.setCreateBy(SecurityUtils.getUser().getName());
				content.setCreateTime(now());
				content.setDelFlag('0'); // 默认为未删除
			});
			itineraryContentService.saveBatch(contentList);
		}
		return itineraryId;
	}
	@Override
	public int removeByItineraryId(Long itineraryId) {
		return trItineraryMapper.removeByItineraryId(itineraryId);
	}

	@Override
	public boolean removeByItineraryIds(Long[] itineraryIds) {
		return trItineraryMapper.removeByItineraryIds(itineraryIds) ;
	}
}
